const fs = require("fs")
const path = require("path")
const { dbConfig } = require("../config")
const Sequelize = require("sequelize")

const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, dbConfig.options)

const db = {}

fs.readdirSync(__dirname)
    .filter(file => file !== "index.js")
    .forEach(file => {
        const model = sequelize.import(path.join(__dirname, file))
        db[model.name] = model
    })

Object.keys(db).forEach(modelName => {
    // 这里主要是将实例化出来的"sequelize"注入到每个子模块(子表)中,让模块之间关联起来
    if (db[modelName].associate) {
        db[modelName].associate(db)
    }
})

db.sequelize = sequelize

module.exports = db
